package com.nyist.myticket.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.nyist.myticket.biz.entity.User;
import com.nyist.myticket.biz.entity.export.TbUserExport;
import com.nyist.myticket.biz.service.TbUserService;
import com.nyist.myticket.core.utils.BeanConvertUtil;
import com.nyist.myticket.core.utils.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * *
 *
 * @author yangxiaogen
 * @date 2021/12/9 14:34
 */
@RestController
/**
 * @RestController
 * 相当于 @Controller + @ResponseBody
 * 返回的时候会自动转成 string,object,json 等实体对象格式, 但是不能直接跳转到 模板页面, 想要跳转需要用 ModelAndView进行封装
 *
 * @Controller
 * 不能直接返回上述的实体对象, 必须加上 @ResponseBody 才可以, 但是可以直接跳转jsp,html页面等模板页面
 *
 * */
@RequestMapping("/export")
@Slf4j
@Api(tags = "一级标题?")
public class ExportController {
    @Autowired
    private TbUserService userService;

    @RequestMapping(path = "/user", method = RequestMethod.GET)
    @ApiOperation(value = "用户导出", notes = "")
    public void exportUserInfo (@RequestParam String id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String parameterName = request.getParameter("name");
        // 设置导出文件名
        String file = "导出测试";
        StringBuilder fileName = new StringBuilder(file);
        fileName.append(parameterName);
        fileName.append(".xls");
        // 设置请求头
        UploadUtil.setFileDownloadHeader(response, fileName.toString());

        // 查询数据
        String name = "sss" + id;
        // log.info("info...",name);
        List<User> queryUserAll = userService.queryUserAll(name);
        // 封装数据到excel
        ArrayList<TbUserExport> exportList = new ArrayList<>();
        for (User user : queryUserAll) {
            TbUserExport userExport = new TbUserExport();
            TbUserExport tbUserExport = BeanConvertUtil.covertBean(user, userExport);
            exportList.add(tbUserExport);
        }

        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("第一个工作簿");
        exportParams.setTitle("标题是啥????");
        // 输出
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TbUserExport.class, exportList);
        workbook.write(response.getOutputStream());

        // 对于 HttpServletResponse 中使用到的文件的下载操作的讲解, 就很棒
        // https://www.cnblogs.com/xdp-gacl/p/3789624.html

    }
}
